package com.jushu.storbox;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.fragment.AllMoveFragment;
import com.jushu.storbox.fragment.BaseFragment;
import com.jushu.storbox.manager.ActivityTaskManager;
import com.jushu.storbox.service.CloudDriveService;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PollingAlarmUtils;

/**
 * 
 * Cloud Drive Main Fragment Activity(FragmentActivity)
 * 
 */
public class AllFileMoveActivity extends Activity {

	/** activity TAG */
	private final static String LOG_TAG = "AllFileMoveActivity";

	private AllMoveFragment allFilePage;

	private long mExitTime = 0l;

	private FragmentManager fragmentManager;

	private BaseFragment currentFragment;

	private int currentIndex = 0;

	private FragmentTransaction transaction;

	public ICloudDriveService shareDriveService;

	private final static int ONCONNECTCOMPLETE = 10;

	/** more title button */
	// private RelativeLayout filelist_tittle_more_top_re;

	private int i_count;

	private int move_icount;

	private FileFolderInfo exInfo;

	private final static int SHAREDFILEFRAGMENT = 0;

	private RelativeLayout main_move_bouttom_cancle_re;
	private RelativeLayout main_move_bouttom_confirm_re;
	private FrameLayout main_buttom_fl;
	private TextView main_tittle_te;
	/***
	 * seervice connection
	 */
	public ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			LogUtil.i(LOG_TAG, "onServiceConnected()");
			shareDriveService = ((CloudDriveService.CenterShareDriveServiceServiceBinder) service)
					.getService();
			if (null != shareDriveService) {
				Message msg = new Message();
				msg.what = ONCONNECTCOMPLETE;
				handler.sendEmptyMessage(msg.what);
			} else {
				System.exit(0);
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			shareDriveService = null;
			LogUtil.e(LOG_TAG, "onServiceDisconnected()");
		}
	};

	@Override
	protected void onResume() {
		LogUtil.i(LOG_TAG, "onResume()");
		if (null != shareDriveService) {
			shareDriveService.checkIsRootAndNotify();
		}
		super.onResume();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		LogUtil.i(LOG_TAG, "onStop()");
		super.onStop();
	}

	/**
	 * onCreate in ShareDriveMainFragmentActivity
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		LogUtil.i(LOG_TAG, "onCreate");
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.share_select_activity);
		ActivityTaskManager.getInstance().putActivity(LOG_TAG,
				AllFileMoveActivity.this);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		bindservice();
		setupView();
		initlistenser();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		LogUtil.i(LOG_TAG, "onDestroy()");
		// TODO Auto-generated method stub
		if (null != shareDriveService) {
			SharedPreferences settings = getSharedPreferences(
					ClientConfig.settings, MODE_APPEND);
			Editor editor = settings.edit();
			// editor.putLong(ClientConfig.SAVEDTIME, 0l);
			editor.putBoolean(ClientConfig.LOGIN_BACKGROUND, false);
			editor.commit();
		}
		if (null != serviceConnection)
			unbindService(serviceConnection);
		PollingAlarmUtils.stopPollingService(AllFileMoveActivity.this, 1,
				"relogin");
		ActivityTaskManager.getInstance().removeActivity(LOG_TAG);
		super.onDestroy();
	}

	private void setupView() {
		main_move_bouttom_cancle_re = (RelativeLayout) findViewById(R.id.main_move_bm_cancle_rl);
		main_move_bouttom_confirm_re = (RelativeLayout) findViewById(R.id.main_move_bm_confirm_rl);
		main_buttom_fl = (FrameLayout) findViewById(R.id.main_move_bm_fl);
		main_tittle_te = (TextView) findViewById(R.id.main_tittle_te);
		main_tittle_te.setText(getString(R.string.my_cloud_drive));
		if (!main_move_bouttom_confirm_re.isClickable()) {
			main_move_bouttom_confirm_re.setClickable(true);
		}
	}

	private void initlistenser() {
		main_move_bouttom_cancle_re.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				BaseFragment mf = currentFragment;
				((AllMoveFragment) currentFragment).moveCancle();

			}
		});
		main_move_bouttom_confirm_re.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Bundle bundle = (Bundle)getIntent().getBundleExtra("moveItem");
				Object srcObj = bundle.get("exinfo");
				((AllMoveFragment) currentFragment).moveConfirm(srcObj);
				if (main_move_bouttom_confirm_re.isClickable()) {
					main_move_bouttom_confirm_re.setClickable(false);
				}
			}
		});
	}

	/***
	 * bind service
	 */
	private void bindservice() {
		Intent intent = new Intent(AllFileMoveActivity.this,
				CloudDriveService.class);
		intent.setAction("tokenAlarm");
		if (null != serviceConnection) {
			bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
		}
	}

	/**
	 * 
	 * @param index
	 */
	private void setTabSelection(int index) {
		if(AllFileMoveActivity.this == null){
			return;
		}
		fragmentManager.popBackStack(null,
				FragmentManager.POP_BACK_STACK_INCLUSIVE);
		i_count = 0;
		Map<String, Object> map = new HashMap<String, Object>();
		transaction = fragmentManager.beginTransaction();
		switch (index) {
		case SHAREDFILEFRAGMENT:
			if (null == allFilePage) {
				allFilePage = new AllMoveFragment();
				transaction.add(R.id.frame_content, allFilePage);
			} else {
				transaction.show(allFilePage);
				if (index != currentIndex) {
					startFragments(allFilePage);
				}
			}
			map.put("service", shareDriveService);
			map.put("activityhandler", handler);
			map.put("moveItem", exInfo);
			map.put("exinfo", null);
			allFilePage.setObj(map);
			currentFragment = allFilePage;
			currentIndex = 0;
			break;
		}
		transaction.commit();
	}

	/**
	 * @param transaction
	 */
	private void stopFragments(Fragment currentFragment) {
		LogUtil.i(LOG_TAG, "stopFragments");
		if (currentFragment != null) {
			currentFragment.onPause();
			currentFragment.onStop();
		}
	}

	/**
	 * @param transaction
	 */
	private void startFragments(Fragment currentFragment) {
		LogUtil.i(LOG_TAG, "startFragments");
		if (currentFragment != null) {
			currentFragment.onStart();
			currentFragment.onResume();
		}
	}

	/**
	 * ShareDriveMainFragmentActivity on key down
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			LogUtil.i(LOG_TAG, "KEYCODE_BACK");
			if (currentFragment.getCanBack()) {
				LogUtil.i(LOG_TAG, "BackStackEntryCount:[onKeyDown]:"
						+ fragmentManager.getBackStackEntryCount());
				if (1 < fragmentManager.getBackStackEntryCount()) {

					fragmentManager.popBackStack();
					i_count -= 1;
					currentFragment = (BaseFragment) fragmentManager
							.findFragmentByTag(i_count + "");
					changeTittle(currentFragment.getParent());
					return true;
				} else if (1 == fragmentManager.getBackStackEntryCount()) {
					changeTittle(getString(R.string.my_cloud_drive));
					i_count = 0;
					switch (currentIndex) {
					case SHAREDFILEFRAGMENT:
						setTabSelection(SHAREDFILEFRAGMENT);
						break;
					default:
						setTabSelection(SHAREDFILEFRAGMENT);
						break;
					}
					return true;
				}
				return super.onKeyDown(keyCode, event);
			}
		}
		return false;
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			BaseFragment fg = null;
			FileFolderInfo infors = null;
			Map<String, Object> map = new HashMap<String, Object>();
			switch (msg.what) {
			case SHAREDFILEFRAGMENT:

				i_count += 1;
				fg = new AllMoveFragment();
				if (null != msg.obj) {
					infors = (FileFolderInfo) msg.obj;
					changeTittle(infors.getName());
				}
				map.put("service", shareDriveService);
				map.put("activityhandler", handler);
				map.put("all_entity", infors);
				map.put("dir", msg.arg1);
				fg.setObj(map);
				currentIndex = SHAREDFILEFRAGMENT;
				transaction = fragmentManager.beginTransaction();
				transaction.setCustomAnimations(
						R.animator.fragment_slide_left_enter,
						R.animator.fragment_slide_left_exit,
						R.animator.fragment_slide_right_enter,
						R.animator.fragment_slide_right_exit);
				transaction.hide(currentFragment);
				transaction.addToBackStack(null);
				transaction.add(R.id.frame_content, fg, i_count + "");
				transaction.commit();
				currentFragment = fg;
				break;
			case 2:
				showMoveUI();
				String titleName = getString(R.string.my_cloud_drive);
				changeTittle(titleName);
				i_count += 1;
				fg = new AllMoveFragment();
				if (null != msg.obj) {
					infors = (FileFolderInfo) msg.obj;
					titleName = infors.getName();
				}
				changeTittle(titleName);
				map.put("service", shareDriveService);
				map.put("activityhandler", handler);
				map.put("move_entity", infors);
				fg.setObj(map);

				currentIndex = 0;
				transaction = fragmentManager.beginTransaction();
				transaction.setCustomAnimations(
						R.animator.fragment_slide_left_enter,
						R.animator.fragment_slide_left_exit,
						R.animator.fragment_slide_right_enter,
						R.animator.fragment_slide_right_exit);
				transaction.hide(currentFragment);
				transaction.addToBackStack(null);
				transaction.add(R.id.frame_content, fg, i_count + "");
				transaction.commit();
				currentFragment = fg;
				if (0 == move_icount) {
					move_icount = i_count;
				}
				break;
			case 8:
				fragmentManager.popBackStack(null,
						FragmentManager.POP_BACK_STACK_INCLUSIVE);
				move_icount = 0;
				break;
			case 9:

				break;
			case ONCONNECTCOMPLETE:
				if (null != shareDriveService) {
					fragmentManager = getFragmentManager();
					setTabSelection(0);
				}
				break;
			default:
				break;
			}
		};
	};

	private void showMoveUI() {
		if (View.GONE == main_buttom_fl.getVisibility()) {
			main_buttom_fl.setVisibility(View.VISIBLE);
		}
	}

	private void changeTittle(String tittleName) {
		if (null != tittleName && 0 < tittleName.length()) {
			main_tittle_te.setText(tittleName);
		} else {
			main_tittle_te.setText(getString(R.string.my_cloud_drive));
		}

		// } else {
		// if (0 == currentIndex) {
		// main_tittle_te.setText(R.string.nav_share_txt);
		// }
		// }

	}
}
